package android.manage;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.main.Main_menu;
import android.main.MemberConst;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.utility.Utility;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.piano_application.R;

/**
 * 관리자 페이지
 * 1. 회원 등록
 * 2. 회원 목록
 * 3. 회원 삭제
 * */
@SuppressLint("HandlerLeak")
public class Management extends Activity implements OnClickListener{
	ProcessGet processGet;
	ProgressDialog pd; 
	
	private String phonenum, name;
	
	private EditText edtPhonenum;
	private EditText edtName;
	
	private ImageButton imgMemList;
	
	private Button btnOK;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_member);       
        
        edtPhonenum = (EditText)findViewById(R.id.edt_phonenum);
        edtPhonenum.setHint("01012345678");
        edtName = (EditText)findViewById(R.id.edt_name);
        edtName.setHint("홍길동");
        
        btnOK = (Button)findViewById(R.id.btn_member_ok);
        btnOK.setOnClickListener(this);
        
        imgMemList = (ImageButton)findViewById(R.id.img_memlist);
        imgMemList.setOnClickListener(this);
	}
		

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.btn_member_ok) {
			saveData();
        } else if(v.getId() == R.id.img_memlist) {
        	Intent intent = null;
			intent = new Intent(getApplicationContext(), Member_list.class);
			startActivity(intent);
        }
		
	}
	
	public void saveData(){
		phonenum = edtPhonenum.getText().toString();
        name = edtName.getText().toString();
        name = Utility.stringToByte(name);
        
        pd = ProgressDialog.show(this, "알림", "데이터를 서버에 저장하고 있습니다.");
        
        String addr = MemberConst.CREATE + "?id=" + phonenum + "&nickname="+name;
        Log.d("d","member addr : "+addr);
        
        processGet = new ProcessGet(addr);
        processGet.start();
        
	}
	
	
	class ProcessGet extends Thread{
        String _addr;

        ProcessGet(String addr) {
            _addr = addr;
        }

        public void run() {

            HttpGet get = new HttpGet(_addr);
            DefaultHttpClient client = new DefaultHttpClient();
            try {
                client.execute(get, responseHandler);
            } 
            catch (Exception e) {;}
        }        
    }
    
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) {
 
            StringBuilder html = new StringBuilder(); 
            String message = "";
            try {                
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while (true) {
                    String line = br.readLine();
                    if (line == null) break;
                    html.append(line + '\n'); 
                }
                br.close();

                JSONObject obj = new JSONObject(html.toString());
                
                String code = obj.getString("code");
                message = obj.getString("message");
                
                if (code.equals("success")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 1;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if (code.equals("fail")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 2;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if ( code.equals("error")){
                	Message msg = msgHandler.obtainMessage();
                    msg.what = 3;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                }
            } catch (Exception e) {
                Message msg = msgHandler.obtainMessage();
                msg.what = 4;
                msg.obj = message;
                msgHandler.sendMessage(msg);
            }
            return html.toString();
        }
    };
	
    Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("D", "handleMessage Call");
            // Log.d("D", "msg.what: " + msg.what);
            
            if (msg.what == 1){
                Management.this.pd.setMessage( (String)msg.obj); 
                if (Management.this.pd != null){
                	Management.this.pd.dismiss();
                    // Toast.makeText(Notice.this, "대화창을 닫습니다.", Toast.LENGTH_LONG).show();
                }
                setResult(RESULT_OK, (new Intent()).setAction("SUCCESS")); // "SUCCESS"를 넘겨준다.
                // 종료 
                
                dialog();
                
//                finish();
            }else if (msg.what == 2){
            	Management.this.pd.setTitle("에러"); 
            	Management.this.pd.setMessage( (String)msg.obj); 
                if (Management.this.pd != null){
                	Management.this.pd.dismiss();
                    // Toast.makeText(Notice.this, "대화창을 닫습니다.", Toast.LENGTH_LONG).show();
                }
                
            }else if (msg.what == 3){
            	Management.this.pd.setTitle("에러"); 
            	Management.this.pd.setMessage( (String)msg.obj); 
                if (Management.this.pd != null){
                	Management.this.pd.dismiss();
                    Toast.makeText(Management.this, "이미 가입된 회원입니다.", Toast.LENGTH_LONG).show();
                }
                
            }else if (msg.what == 4){
            	Management.this.pd.setTitle("에러"); 
            	Management.this.pd.setMessage( (String)msg.obj); 
                if (Management.this.pd != null){
                	Management.this.pd.dismiss();
                }
                
            }            
        }
    };
	
	public void dialog(){
		AlertDialog dialog = createDialogBox();
		dialog.show();
	}
	
	private AlertDialog createDialogBox(){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle("안내");
		builder.setMessage("회원등록이 완료되었습니다.");
		
		builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Intent intent = null;
    			intent = new Intent(getApplicationContext(), Main_menu.class);
    			startActivity(intent);
    			finish();
			}
		});
		
		AlertDialog dialog = builder.create();
		return dialog;
	}
			
}
